import os

import ddddocr  # 导入 ddddocr
from PIL import Image
from selenium.webdriver.common.by import By

from config.config import  base_path
def img_decoder(img):
    ocr = ddddocr.DdddOcr(show_ad=False)  # 实例化
    with open(img, 'rb') as f:  # 打开图片
        img_bytes = f.read()  # 读取图片
    res = ocr.classification(img_bytes)  # 识别
    return res

def get_ele_box(element):
    rect = element.rect
    # 处理截图:left, upper, right, and lower
    box = (rect['x'], rect['y'], rect['x'] + rect['width'], rect['y'] + rect['height'])
    return box
def get_captcha(driver,id):
    #浏览器截图
    sh_img = os.path.join(base_path,"screenshots","sh.png")
    driver.save_screenshot(sh_img)
    #获取指定id元素的抠图
    el = driver.find_element(by=By.ID, value=id)
    box = get_ele_box(el)
    crop_img = os.path.join(base_path,"screenshots","crop.png")
    im = Image.open(sh_img)
    im.crop(box).save(crop_img)
    #解码
    code = img_decoder(crop_img)
    return code

